//
//  UIImage+Test.m
//  testImage
//
//  Created by lianglibao on 2018/7/4.
//  Copyright © 2018年 lianglibao. All rights reserved.
//

#import "UIImage+Test.h"
#import <MobileCoreServices/MobileCoreServices.h>

@implementation UIImage (Test)
- (UIImage *)raz_scaleImageToFitScreenSize {
    CGSize curScreenSize = [UIScreen mainScreen].bounds.size;
    CGFloat curScreenSale = [UIScreen mainScreen].scale;
    CGSize targetImageSize = CGSizeMake(self.size.width * (curScreenSize.width / 1024), self.size.height * (curScreenSize.height / 768));
    
    CGFloat scale = [[UIScreen mainScreen] scale];
    targetImageSize = CGSizeMake(flatSpecificScale(targetImageSize.width, scale), flatSpecificScale(targetImageSize.height, scale));
    CGSize imageSize = self.size;
    CGRect drawingRect = CGRectZero;
    
    CGFloat ratio = imageSize.height / (targetImageSize.height);
    drawingRect.size.width = imageSize.width / ratio;
    drawingRect.size.height = imageSize.height / ratio;
    
    return [self scaledImageToWidth:drawingRect.size.width];
}

- (UIImage *)scaledImageToSize:(CGSize)targetSize {
    CGFloat horizontalRatio = self.size.width * 1.0f / targetSize.width;
    CGFloat verticalRatio = self.size.height * 1.0f / targetSize.height;
    CGFloat tmpW = 0;
    if (horizontalRatio < verticalRatio) {
        tmpW = self.size.height / horizontalRatio;
    } else if (horizontalRatio > verticalRatio) {
        tmpW = self.size.width / verticalRatio;
    } else {
        tmpW = targetSize.width;
    }

   return [self scaledImageToWidth:tmpW];
}

// MARK: - 缩放图片为指定宽度,高度会对应等比缩放.
- (UIImage *)scaledImageToWidth:(CGFloat)width {
    if (width <=0) {
        return [[UIImage alloc] init];
    }
    CGFloat scale = [UIScreen mainScreen].scale;
    NSData *data = [UIImage imageDataWithImage:self];
    CGImageSourceRef source = CGImageSourceCreateWithData((__bridge CFDataRef)(data), nil);
    CFDictionaryRef options = (__bridge CFDictionaryRef) @{
                                                            (id)kCGImageSourceCreateThumbnailFromImageIfAbsent : @(YES),
                                                           (id)kCGImageSourceShouldCache : @(YES),
                                                           (id) kCGImageSourceThumbnailMaxPixelSize : @(scale * width)
                                                           };
    CGImageRef scaledImageRef = CGImageSourceCreateThumbnailAtIndex(source, 0, options);
    UIImage *scaled = [UIImage imageWithCGImage:scaledImageRef
                                          scale:scale
                                    orientation:UIImageOrientationUp];
    CGImageRelease(scaledImageRef);
    return scaled;
}

- (UIImage *)scaleImageToSize:(CGSize)size {
    CGFloat scale = [[UIScreen mainScreen] scale];
    size = CGSizeMake(flatSpecificScale(size.width, scale), flatSpecificScale(size.height, scale));
    CGSize imageSize = self.size;
    CGRect drawingRect = CGRectZero;
    
    CGFloat sizeRatio = size.width / size.height;
    CGFloat imageRatio = imageSize.width / imageSize.height;
    
    if (sizeRatio > imageRatio) {
        drawingRect.size.height = size.height;
        drawingRect.size.width = imageSize.width * drawingRect.size.height / imageSize.height;
    } else {
        drawingRect.size.width = size.width;
        drawingRect.size.height = imageSize.height * drawingRect.size.width / imageSize.width;
    }
    
    CGImageAlphaInfo alphaInfo = CGImageGetAlphaInfo(self.CGImage);
    BOOL opaque = alphaInfo == kCGImageAlphaNoneSkipLast || alphaInfo == kCGImageAlphaNoneSkipFirst ||
    alphaInfo == kCGImageAlphaNone;
    
    UIGraphicsBeginImageContextWithOptions(drawingRect.size, opaque, scale);
    UIGraphicsGetCurrentContext();
    [self drawInRect:drawingRect];
    UIImage *imageOut = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    if (imageOut == nil) {
        NSLog(@"图片缩放失败，image:%@", self);
        //图片缩放失败原样返回
        return self;
    } else {
        return imageOut;
    }
}


CG_INLINE CGFloat
flatSpecificScale(CGFloat floatValue, CGFloat scale) {
    scale = scale == 0 ? ([[UIScreen mainScreen] scale]) : scale;
    CGFloat flattedValue = ceil(floatValue * scale) / scale;
    return flattedValue;
}

//CG_INLINE CGFloat
//flat(CGFloat floatValue) {
//    return flatSpecificScale(floatValue, 0);
//}

- (UIImage *)cutImageWithIndex:(int)index {
    __block UIImage* finalImage = nil;
    CGImageRef imageRef = self.CGImage;
    size_t width = CGImageGetWidth(imageRef);
    size_t height = CGImageGetHeight(imageRef);
    
    NSLog(@"%zu++=========++%zu", width, height);
    
    CGFloat perWidth = [UIScreen mainScreen].bounds.size.width * [UIScreen mainScreen].scale;
    CGImageRef newImageRef = CGImageCreateWithImageInRect(imageRef, CGRectMake(index * perWidth, 0, perWidth, height));//按照给定的矩形区域进行剪裁
    finalImage = [UIImage imageWithCGImage:newImageRef];
    return finalImage;
}

+ (void)saveCacheImage:(UIImage *)image cacheFilePath:(NSString *)cacheFilePath {
    if (!image || !cacheFilePath) { return ; }
    if ([NSThread isMainThread]) {
        dispatch_async(dispatch_get_global_queue(0, 0), ^{
            [self saveCacheImage:image cacheFilePath:cacheFilePath];
        });
    } else {
        [self savingCacheImage:image cacheFilePath:cacheFilePath];
    }
}

+ (void)savingCacheImage:(UIImage *)image cacheFilePath:(NSString *)cacheFilePath {
    BOOL write = [[self imageDataWithImage:image] writeToFile:cacheFilePath atomically:YES];
    if (write) {
        NSLog(@"image write succeed");
    } else {
        NSLog(@"image write failed");
    }
}

// MARK: COPY FROM SDWebImage
+ (NSData *)imageDataWithImage:(UIImage *)image {
    CGImageAlphaInfo alphaInfo = CGImageGetAlphaInfo(image.CGImage);
    
    BOOL hasAlpha = !((alphaInfo == kCGImageAlphaNone) ||
                      (alphaInfo == kCGImageAlphaNoneSkipFirst) ||
                      (alphaInfo == kCGImageAlphaNoneSkipLast));
    
    CFStringRef imageUTType;
    if (hasAlpha) {
        imageUTType = kUTTypePNG;
        // PNG
        // return UIImagePNGRepresentation(image);
    } else {
        // JPEG
        imageUTType = kUTTypeJPEG;
        // return UIImageJPEGRepresentation(image, 1.0);
    }
    NSMutableData *imageData = [NSMutableData data];
    
    // Create an image destination.
    CGImageDestinationRef imageDestination = CGImageDestinationCreateWithData((__bridge CFMutableDataRef)imageData, imageUTType, 1, NULL);
    if (!imageDestination) {
        // Handle failure.
        return nil;
    }
    
    NSMutableDictionary *properties = [NSMutableDictionary dictionary];
    NSInteger exifOrientation = [self exifOrientationFromImageOrientation:image.imageOrientation];
    [properties setValue:@(exifOrientation) forKey:(__bridge_transfer NSString *)kCGImagePropertyOrientation];
    
    // Add your image to the destination.
    CGImageDestinationAddImage(imageDestination, image.CGImage, (__bridge CFDictionaryRef)properties);
    
    // Finalize the destination.
    if (CGImageDestinationFinalize(imageDestination) == NO) {
        // Handle failure.
        imageData = nil;
    }
    
    CFRelease(imageDestination);
    
    return [imageData copy];
}

// Convert an iOS orientation to an EXIF image orientation.
+ (NSInteger)exifOrientationFromImageOrientation:(UIImageOrientation)imageOrientation {
    // CGImagePropertyOrientation is available on iOS 8 above. Currently kept for compatibility
    NSInteger exifOrientation = 1;
    switch (imageOrientation) {
        case UIImageOrientationUp:
            exifOrientation = 1;
            break;
        case UIImageOrientationDown:
            exifOrientation = 3;
            break;
        case UIImageOrientationLeft:
            exifOrientation = 8;
            break;
        case UIImageOrientationRight:
            exifOrientation = 6;
            break;
        case UIImageOrientationUpMirrored:
            exifOrientation = 2;
            break;
        case UIImageOrientationDownMirrored:
            exifOrientation = 4;
            break;
        case UIImageOrientationLeftMirrored:
            exifOrientation = 5;
            break;
        case UIImageOrientationRightMirrored:
            exifOrientation = 7;
            break;
        default:
            break;
    }
    return exifOrientation;
}

@end
